<template>
  <div class="home-page">
    <Header />
    
    <!-- Hero Section with Background Image -->
    <section class="hero-section" :style="heroSectionStyle">
      <div class="hero-overlay">
        <h1 class="hero-title">{{ homeInfo?.titleEn || 'Multimodal Health Data and Aging Lab' }}</h1>
      </div>
    </section>

    <!-- Three Column Layout -->
    <main class="page-content">
      <div class="container">
        <div class="three-column-layout">
          <!-- Left Column: Introduction & Research Areas -->
          <section class="column left-column">
            <div class="intro-section">
              <h2 class="column-title">Introduction</h2>
              <!-- <div v-if="homeInfo?.banner_url" class="intro-image">
                <img :src="getImageUrl(homeInfo.banner_url)" :alt="homeInfo.titleEn">
              </div> -->
              <div class="column-content">
                <p v-html="homeInfo?.introduction || ''"></p>
              </div>
            </div>

            <div class="research-areas-section">
              <h2 class="column-title">Research Areas</h2>
              <div class="column-content">
                <div class="research-areas-grid">
                  <div 
                    v-for="(area, index) in displayResearchAreas" 
                    :key="area.content_id" 
                    class="research-area-item"
                    :class="{ 'last-odd-item': isLastOddItem(index) }"
                  >
                    <h3>{{ area.title }}</h3>
                    <div v-if="area.image_url" class="area-image">
                      <img :src="getImageUrl(area.image_url)" :alt="area.title">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

          <!-- Middle Column: News -->
          <section class="column middle-column">
            <h2 class="column-title">News</h2>
            <div class="column-content">
              <div v-if="newsLoading" class="loading">加载中...</div>
              <div v-else-if="newsError" class="error">{{ newsError }}</div>
              <div v-else>
                <div class="news-list">
                  <article v-for="item in newsList" :key="item.content_id" class="news-item">
                    <div class="news-content">
                      <div class="news-text">
                        <h2 
                          class="news-title-link"
                          @click="goToDetail('news', item.content_id)"
                        >
                          {{ item.title }}
                        </h2>
                        <p class="news-date">{{ formatDate(item.content_date) }}</p>
                        <p class="news-excerpt">{{ item.introduction }}</p>
                        <a 
                          :href="`/news/detail?type=news&id=${item.content_id}`" 
                          class="read-more"
                          @click.prevent="goToDetail('news', item.content_id)"
                        >
                          Read More »
                        </a>
                      </div>
                      <div 
                        v-if="item.image_url" 
                        class="news-image"
                        @click="goToDetail('news', item.content_id)"
                      >
                        <img :src="getImageUrl(item.image_url)" :alt="item.title">
                      </div>
                    </div>
                  </article>
                </div>

                <!-- News Pagination -->
                <div v-if="!newsLoading && !newsError" class="pagination">
                  <a 
                    v-if="newsCurrentPage > 1"
                    href="#" 
                    class="pagination-link" 
                    @click.prevent="prevNewsPage"
                  >
                    « Previous
                  </a>
                  <span v-else class="pagination-disabled">« Previous</span>
                  
                  <a 
                    v-if="newsCurrentPage < newsTotalPages"
                    href="#" 
                    class="pagination-link" 
                    @click.prevent="nextNewsPage"
                  >
                    Next »
                  </a>
                  <span v-else class="pagination-disabled">Next »</span>
                </div>
              </div>
            </div>
          </section>

          <!-- Right Column: Recent Results -->
          <section class="column right-column">
            <h2 class="column-title">Recent Results</h2>
            <div class="column-content">
              <div v-if="resultsLoading" class="loading">加载中...</div>
              <div v-else-if="resultsError" class="error">{{ resultsError }}</div>
              <div v-else>
                <div class="results-list">
                  <article v-for="item in resultsList" :key="item.content_id" class="result-item">
                    <div class="result-content">
                      <div class="result-text">
                        <h3 
                          class="result-title-link"
                          @click="goToDetail('result', item.content_id)"
                        >
                          {{ item.title }}
                        </h3>
                        <p class="result-date">{{ formatDate(item.content_date) }}</p>
                        <p class="result-excerpt">{{ item.introduction }}</p>
                        <a 
                          :href="`/news/detail?type=result&id=${item.content_id}`" 
                          class="read-more"
                          @click.prevent="goToDetail('result', item.content_id)"
                        >
                          Read More »
                        </a>
                      </div>
                      <div 
                        v-if="item.image_url" 
                        class="result-image"
                        @click="goToDetail('result', item.content_id)"
                      >
                        <img :src="getImageUrl(item.image_url)" :alt="item.title">
                      </div>
                    </div>
                  </article>
                </div>

                <!-- Results Pagination -->
                <div v-if="!resultsLoading && !resultsError" class="pagination">
                  <a 
                    v-if="resultsCurrentPage > 1"
                    href="#" 
                    class="pagination-link" 
                    @click.prevent="prevResultsPage"
                  >
                    « Previous
                  </a>
                  <span v-else class="pagination-disabled">« Previous</span>
                  
                  <a 
                    v-if="resultsCurrentPage < resultsTotalPages"
                    href="#" 
                    class="pagination-link" 
                    @click.prevent="nextResultsPage"
                  >
                    Next »
                  </a>
                  <span v-else class="pagination-disabled">Next »</span>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </main>
    
    <Footer />
  </div>
</template>

<script>
import Header from '../components/Header.vue'
import Footer from '../components/Footer.vue'
import { getHomeInfo, getNewsList, getResultList, getResearchList, API_BASE_URL } from '@/utils/api'

export default {
  name: 'Home',
  components: {
    Header,
    Footer
  },
  data() {
    return {
      // Home Info数据
      homeInfo: null,
      homeLoading: false,
      homeError: null,
      
      // News数据
      newsList: [],
      newsCurrentPage: 1,
      newsPerPage: 5,
      newsTotal: 0,
      newsTotalPages: 1,
      newsLoading: false,
      newsError: null,
      
      // Results数据
      resultsList: [],
      resultsCurrentPage: 1,
      resultsPerPage: 5,
      resultsTotal: 0,
      resultsTotalPages: 1,
      resultsLoading: false,
      resultsError: null,
      
      // Research数据
      researchAreas: [],
      researchLoading: false,
      researchError: null
    }
  },
  computed: {
    heroSectionStyle() {
      if (this.homeInfo?.banner_url) {
        return {
          backgroundImage: `url(${this.getImageUrl(this.homeInfo.banner_url)})`
        }
      }
      return {}
    },
    displayResearchAreas() {
      // 只显示前4条
      return this.researchAreas.slice(0, 4)
    }
  },
  async mounted() {
    await Promise.all([
      this.fetchHomeInfo(),
      this.fetchNewsList(),
      this.fetchResultsList(),
      this.fetchResearchList()
    ])
  },
  methods: {
    /**
     * 获取Home信息
     */
    async fetchHomeInfo() {
      this.homeLoading = true
      this.homeError = null
      try {
        this.homeInfo = await getHomeInfo()
      } catch (error) {
        console.error('获取Home信息失败:', error)
        this.homeError = error.message || '获取首页信息失败'
        this.homeInfo = null
      } finally {
        this.homeLoading = false
      }
    },
    
    /**
     * 获取News列表
     */
    async fetchNewsList() {
      this.newsLoading = true
      this.newsError = null
      try {
        const data = await getNewsList(this.newsCurrentPage, this.newsPerPage)
        this.newsList = data.list || []
        this.newsTotal = data.total || 0
        this.newsTotalPages = data.last_page || 1
        this.newsCurrentPage = data.current_page || 1
      } catch (error) {
        console.error('获取News列表失败:', error)
        this.newsError = error.message || '获取新闻列表失败'
        this.newsList = []
      } finally {
        this.newsLoading = false
      }
    },
    
    /**
     * 获取Results列表
     */
    async fetchResultsList() {
      this.resultsLoading = true
      this.resultsError = null
      try {
        const data = await getResultList(this.resultsCurrentPage, this.resultsPerPage)
        this.resultsList = data.list || []
        this.resultsTotal = data.total || 0
        this.resultsTotalPages = data.last_page || 1
        this.resultsCurrentPage = data.current_page || 1
      } catch (error) {
        console.error('获取Results列表失败:', error)
        this.resultsError = error.message || '获取成果列表失败'
        this.resultsList = []
      } finally {
        this.resultsLoading = false
      }
    },
    
    /**
     * 获取Research列表
     */
    async fetchResearchList() {
      this.researchLoading = true
      this.researchError = null
      try {
        const data = await getResearchList()
        this.researchAreas = data.list || []
      } catch (error) {
        console.error('获取Research列表失败:', error)
        this.researchError = error.message || '获取研究方向列表失败'
        this.researchAreas = []
      } finally {
        this.researchLoading = false
      }
    },
    
    /**
     * News分页：上一页
     */
    async prevNewsPage() {
      if (this.newsCurrentPage > 1) {
        this.newsCurrentPage--
        await this.fetchNewsList()
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    },
    
    /**
     * News分页：下一页
     */
    async nextNewsPage() {
      if (this.newsCurrentPage < this.newsTotalPages) {
        this.newsCurrentPage++
        await this.fetchNewsList()
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    },
    
    /**
     * Results分页：上一页
     */
    async prevResultsPage() {
      if (this.resultsCurrentPage > 1) {
        this.resultsCurrentPage--
        await this.fetchResultsList()
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    },
    
    /**
     * Results分页：下一页
     */
    async nextResultsPage() {
      if (this.resultsCurrentPage < this.resultsTotalPages) {
        this.resultsCurrentPage++
        await this.fetchResultsList()
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    },
    
    /**
     * 格式化日期
     */
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('en-US', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
      })
    },
    
    /**
     * 获取图片完整URL
     */
    getImageUrl(imageUrl) {
      if (!imageUrl) return ''
      if (imageUrl.startsWith('http')) {
        return imageUrl
      }
      // Research接口返回的image_url格式为 "images/2025/11/15/..."，需要添加 /upload/ 前缀
      if (imageUrl.startsWith('images/')) {
        return `${API_BASE_URL}/upload/${imageUrl}`
      }
      // 如果image_url是以/开头，直接使用
      if (imageUrl.startsWith('/')) {
        return `${API_BASE_URL}${imageUrl}`
      }
      // 其他情况，添加/前缀
      return `${API_BASE_URL}/${imageUrl}`
    },
    
    /**
     * 跳转到详情页（新标签页打开）
     */
    goToDetail(type, contentId) {
      const url = `/news/detail?type=${type}&id=${contentId}`
      window.open(url, '_blank')
    },
    
    /**
     * 判断是否是最后一个奇数项
     */
    isLastOddItem(index) {
      return this.displayResearchAreas.length % 2 !== 0 && index === this.displayResearchAreas.length - 1
    }
  }
}
</script>

<style scoped>
.home-page {
  background-color: #fff;
}

.hero-section {
  position: relative;
  height: 600px;
  background: url('/default_banner.png') center/cover;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.hero-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.hero-overlay {
  position: relative;
  z-index: 1;
  text-align: center;
  padding: 40px;
}

.hero-title {
  font-size: 3.5em;
  color: #fff;
  font-weight: normal;
  line-height: 1.4;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.page-content {
  padding: 60px 0 20px 0;
  background-color: #fff;
}

.three-column-layout {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 40px;
}

.column {
  min-height: 400px;
}

.column-title {
  font-size: 1.8em;
  color: #333;
  font-weight: normal;
  padding-bottom: 15px;
  margin-bottom: 25px;
  border-bottom: 2px solid #e0e0e0;
}

.column-content {
  color: var(--text-color);
  line-height: 1.8;
}

/* Left Column - Introduction & Research Areas */
.left-column .intro-section {
  margin-bottom: 50px;
}

.intro-image {
  margin-bottom: 20px;
  overflow: hidden;
  border-radius: 8px;
}

.intro-image img {
  width: 100%;
  height: auto;
  display: block;
}

.column-content p {
  margin-bottom: 15px;
  font-size: 0.95em;
}

/* Research Areas */
.research-areas-section {
  margin-top: 50px;
}

.research-areas-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 25px;
}

.research-area-item {
  display: flex;
  flex-direction: column;
}

.research-area-item h3 {
  font-size: 1.05em;
  color: #333;
  margin-bottom: 12px;
  font-weight: 600;
  text-align: center;
}

.area-image {
  overflow: hidden;
  border-radius: 8px;
  flex: 1;
  display: inline-block;
}

.area-image img {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
  transition: transform 0.3s ease;
}

.area-image:hover img {
  transform: scale(1.05);
}

/* Last item when total is odd - spans full width */
.research-area-item.last-odd-item {
  grid-column: 1 / -1;
}

.research-area-item.last-odd-item h3 {
  font-size: 1.2em;
  margin-bottom: 15px;
}

.research-area-item.last-odd-item .area-image {
  height: 250px;
}

/* Middle Column - News */
.news-list {
  display: flex;
  flex-direction: column;
  gap: 35px;
}

.news-item {
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 30px;
}

.news-item:last-child {
  border-bottom: none;
}

.news-content {
  display: flex;
  gap: 20px;
}

.news-text {
  flex: 1;
  min-width: 0;
}

.news-text h2 {
  font-size: 1.1em;
  color: #333;
  margin: 0 0 10px 0;
  font-weight: 600;
  line-height: 1.5;
}

.news-title-link {
  cursor: pointer;
  transition: color 0.3s ease;
}

.news-title-link:hover {
  color: var(--primary-color);
}

.news-date {
  color: #999;
  font-size: 0.85em;
  margin: 0 0 10px 0;
}

.news-excerpt {
  font-size: 0.9em;
  color: var(--text-color);
  margin: 0 0 12px 0;
  line-height: 1.6;
}

.news-image {
  flex-shrink: 0;
  width: 150px;
  display: inline-block;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.news-image:hover {
  opacity: 0.8;
}

.news-image img {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
  transition: transform 0.3s ease;
}

.news-image:hover img {
  transform: scale(1.05);
}

/* Right Column - Recent Results */
.results-list {
  display: flex;
  flex-direction: column;
  gap: 35px;
}

.result-item {
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 30px;
}

.result-item:last-child {
  border-bottom: none;
}

.result-content {
  display: flex;
  gap: 20px;
}

.result-text {
  flex: 1;
  min-width: 0;
}

.result-text h3 {
  font-size: 1.1em;
  color: #333;
  margin: 0 0 10px 0;
  font-weight: 600;
  line-height: 1.5;
}

.result-title-link {
  cursor: pointer;
  transition: color 0.3s ease;
}

.result-title-link:hover {
  color: var(--primary-color);
}

.result-image {
  flex-shrink: 0;
  width: 150px;
  display: inline-block;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.result-image:hover {
  opacity: 0.8;
}

.result-image img {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
  transition: transform 0.3s ease;
}

.result-image:hover img {
  transform: scale(1.05);
}

.result-date {
  color: #999;
  font-size: 0.85em;
  margin: 0 0 10px 0;
}

.result-excerpt {
  font-size: 0.9em;
  color: var(--text-color);
  margin: 0 0 12px 0;
  line-height: 1.6;
}

/* Common Styles */
.read-more {
  color: var(--primary-color);
  font-weight: 500;
  transition: color 0.3s ease;
  display: inline-block;
  font-size: 0.9em;
}

.read-more:hover {
  color: var(--hover-color);
  text-decoration: underline;
}

.loading {
  text-align: center;
  padding: 40px 0;
  color: #666;
  font-size: 1em;
}

.error {
  text-align: center;
  padding: 40px 0;
  color: #e74c3c;
  font-size: 1em;
}

/* Pagination Styles */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
  padding-top: 25px;
  border-top: 1px solid var(--border-color);
}

.pagination-link {
  color: var(--primary-color);
  font-weight: 500;
  font-size: 0.95em;
  text-decoration: none;
  transition: all 0.3s ease;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 3px;
}

.pagination-link:hover {
  color: white;
  background-color: var(--primary-color);
  text-decoration: none;
}

.pagination-disabled {
  color: #ccc;
  font-size: 0.95em;
  cursor: default;
  padding: 5px 10px;
}

/* Responsive Design */
@media (max-width: 1024px) {
  .three-column-layout {
    grid-template-columns: 1fr;
    gap: 50px;
  }
  
  .hero-title {
    font-size: 2.5em;
  }
  
  .news-content {
    flex-direction: column;
  }
  
  .news-image {
    width: 100%;
  }
  
  .result-content {
    flex-direction: column;
  }
  
  .result-image {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .hero-section {
    height: 400px;
  }
  
  .hero-title {
    font-size: 1.8em;
  }
  
  .page-content {
    padding: 40px 0;
  }
  
  .three-column-layout {
    gap: 40px;
  }
  
  .pagination {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .research-areas-grid {
    grid-template-columns: 1fr;
  }
  
  .research-area-item.last-odd-item .area-image {
    height: 200px;
  }
}
</style>

